package com.kd.juhaowan.sdk;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import com.kedou.sdk.JuHaoWanSDK;
import com.kedou.sdk.JuHaoWanSDKCallback;
import com.kedou.sdk.download.VersionUpdateDownloader;
import com.kedou.sdk.params.bean.Goods;
import com.kedou.sdk.params.bean.RoleInfo;
import com.kedou.sdk.params.bean.RoleStatus;
import com.kedou.sdk.utils.WL;

import java.io.File;

public class MainActivity extends Activity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private TextView version;
    private Button login;
//    BillingClient billingClient;
    private boolean isConnect;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        hideVirtualKeysAndFullScreen();
        WL.writeLogs(true);

        setContentView(getResources().getIdentifier("activity_main", "layout", getPackageName()));

        version = (TextView) findViewById(getResources().getIdentifier("version_text", "id", getPackageName()));
        version.setText(getVersionName());

        login = findViewById(getResources().getIdentifier("login_test", "id", getPackageName()));
        JuHaoWanSDK.getInstance().onCreate(this);
//        WanSDK.getInstance().initToutiao(this,"608675");


    }

//    private void query(){
//        String productId ="1"; //请替换成自己的商品id
//        List<QueryProductDetailsParams.Product> productList= new ArrayList<>();
//        productList.add(QueryProductDetailsParams.Product.newBuilder()
//                .setProductId(productId)
//                .setProductType(BillingClient.ProductType.INAPP)
//                .build());
//        QueryProductDetailsParams queryProductDetailsParams = QueryProductDetailsParams.newBuilder().
//                setProductList(productList)
//                .build();
//        if(billingClient!=null){
//            billingClient.queryProductDetailsAsync(
//                    queryProductDetailsParams,
//                    new ProductDetailsResponseListener() {
//                        public void onProductDetailsResponse(BillingResult billingResult,
//                                                             List<ProductDetails> productDetailsList) {
//                            pay(productDetailsList.get(0));
//                        }
//                    }
//            );
//        }
//    }

//    private void pay(ProductDetails productDetails){
////        ProductDetails productDetails=productDetailsList.get(0);
//        List<BillingFlowParams.ProductDetailsParams> productDetailsParamsList= new ArrayList<>();
//        productDetailsParamsList.add(BillingFlowParams.ProductDetailsParams.newBuilder()
//                .setProductDetails(productDetails)
//
//                .build());
//        BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
//                .setProductDetailsParamsList(productDetailsParamsList)
//                .setObfuscatedAccountId("3434343434")
//                .build();
//        billingClient.launchBillingFlow(MainActivity.this, billingFlowParams);
//    }

    String getVersionName() {
        try {
            PackageManager pm = getPackageManager();
            PackageInfo info = null;
            info = pm.getPackageInfo(getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    public void openFloatWindow(View v) {
        JuHaoWanSDK.getInstance().openWindow();
    }

    public void closeFloatWindow(View v) {
        JuHaoWanSDK.getInstance().closeWindow();
    }

    @Override
    public void onBackPressed() {
        JuHaoWanSDK.getInstance().onBackPressed();
        //super.onBackPressed();
        JuHaoWanSDK.getInstance().exitApp(this);
//        BillingFlowParams.ProductDetailsParams.newBuilder()
//                // retrieve a value for "productDetails" by calling queryProductDetailsAsync()
//                .setProductDetails(null)
////                .
//                // to get an offer token, call ProductDetails.getSubscriptionOfferDetails()
//                // for a list of offers that are available to the user
////                .setOfferToken(selectedOfferToken)
//                .build();
//        BillingFlowParams.newBuilder()
//                .setProductDetailsParamsList(null)
//                .setObfuscatedAccountId()
//                .build();


    }

    public void onLoginTest(View v) {
        JuHaoWanSDK juHaoWanSDK = JuHaoWanSDK.getInstance();
        if (!juHaoWanSDK.isLoggedIn()) {
            juHaoWanSDK.login(new JuHaoWanSDKCallback(){
                @Override
                public void onWanSDKResponse(int stateCode, String s, String s1) {
                    if (1 == stateCode || 4 == stateCode) {
                        //登录成功 以json形式返回用户信息uid，ticket，expiresin
                        //示例：{"uid":"1061758","ticket":"5ce0c0a17838375fba109d44d202f97b","expiresIn":7200}

                    } else if (2 == stateCode) {
                        //取消登录操作

                    }else if (5 ==stateCode){
                        //登出操作
                    }else {
                        //登录失败
                    }
                }

                @Override
                public void onWanSDKException(Exception e) {
                    //登录失败
                }
            });
        } else {
            juHaoWanSDK.logout();
            login.setText("登录（测试）");
        }
    }

    public void uploadRoleInfo(View v) {
        RoleInfo roleinfo = new RoleInfo();
        roleinfo.setRoleLevel("11");
        roleinfo.setServerId("1085");
        roleinfo.setServerName("995测试区");
        roleinfo.setRoleName("杭高岑");
        roleinfo.setRoleId("65542");
        JuHaoWanSDK.getInstance().uploadRoleInfo(roleinfo, RoleStatus.UPGRADE, new JuHaoWanSDKCallback() {
            @Override
            public void onWanSDKResponse(int i, String s, String s1) {

            }

            @Override
            public void onWanSDKException(Exception e) {

            }
        });

    }
//
//    public void queryPreventAddictionInfo(View v) {
//        WanSDK.getInstance().queryPreventAddictionInfo(new Callback());
//    }

    public void onMobliePayTest(View v) {
        Goods goods = new Goods("60灵玉", 100000);
        goods.setGoodsId("1");
        goods.setGoodsDesc("购买60灵玉");
        goods.setServerId(100);
        goods.setServerName("双线二服");
        goods.setRoleId("5456");
        goods.setRoleName("测试角色");
        goods.setGainCount(1);
        goods.setExtraData("A510531805265734");//研发订单号等相关信息，

        JuHaoWanSDK.getInstance().pay(goods, new JuHaoWanSDKCallback() {
            @Override
            public void onWanSDKResponse(int stateCode, String s, String s1) {
                if (1 == stateCode) {
                    //支付成功
                    Toast.makeText(MainActivity.this,"支付成功",Toast.LENGTH_SHORT).show();
                } else if (2 == stateCode) {
                    //支付取消
                } else if (4 == stateCode) {
                    //未登录

                } else if (5 == stateCode) {
                    //未知错误
                } else {
                    //支付失败
                }
            }

            @Override
            public void onWanSDKException(Exception e) {

            }
        });
//        WanSDK.getInstance().pay(goods, MainActivity.this,new Callback());
    }

    public void deleteDownloadApkFile(View view) {
        File file = VersionUpdateDownloader.getImpl().getDownloadApkVersionFile();
        if (file != null && file.delete()) {
            Toast.makeText(this, "删除下载文件成功！", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "删除下载文件失败！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        JuHaoWanSDK.getInstance().onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        WL.d(TAG,"onResume");
        JuHaoWanSDK.getInstance().onResume();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        JuHaoWanSDK.getInstance().onRestart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JuHaoWanSDK.getInstance().onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        JuHaoWanSDK.getInstance().onStop();
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        JuHaoWanSDK.getInstance().onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        JuHaoWanSDK.getInstance().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        JuHaoWanSDK.getInstance().onConfigurationChanged(newConfig);
    }

    protected void hideVirtualKeysAndFullScreen() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

//    private class Callback implements WanSDKCallback {
//
//        @Override
//        public void onWanSDKResponse(int stateCode, String message, String jsonObject) {
//            StringBuilder builder = new StringBuilder();
//            builder.append("code: ").append(stateCode).append(" ,message: ").append(message);
//            if (jsonObject != null) {
//                builder.append(" ,data: ").append(jsonObject);
//                if (!TextUtils.isEmpty(jsonObject)) {
//                    login.setText("登出（测试）");
//                }
//            }
//            Toast.makeText(MainActivity.this, builder.toString(), Toast.LENGTH_LONG).show();
//            Log.d(TAG, "jsonObject: " + builder.toString());
//        }
//
//        @Override
//        public void onWanSDKException(Exception ex) {
//            if (ex instanceof NetworkErrorException) {
//                Toast.makeText(MainActivity.this, "NetworkErrorException", Toast.LENGTH_LONG).show();
//            } else if (ex instanceof IOException) {
//                Toast.makeText(MainActivity.this, "IOException", Toast.LENGTH_LONG).show();
//            } else {
//                Toast.makeText(MainActivity.this, "OtherException", Toast.LENGTH_LONG).show();
//            }
//        }
//    }

}
